



<template>
  <div class="app-container">

      <div class="head-container">
        <div class="tip">
          <p>此处为采集互联网的原文素材，不可直接发布，您可以选择单篇/批量/全量 洗稿，可在洗稿任务中查看任务完成进度，完成后在文章稿件可查看洗稿后的文章</p>
        </div>
      </div>
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">洗前配置：</el-col>-->
      <el-divider content-position="left">洗稿配置</el-divider>
      <el-col :span="1.5">
        <el-switch
          v-model="tuswitch"
          active-text=""
          inactive-text="是否修改文中图顺序">
        </el-switch>
      </el-col>
      <el-col :span="1.5">
        <el-switch
          v-model="xituSwitch"
          active-text=""
          @change="switchXituChange"
          inactive-text="是否附带洗图">
        </el-switch>
      </el-col>
      <el-col :span="1.5">
        每篇素材洗出数量
        <el-input-number size="mini" v-model="oneToNum"></el-input-number>
      </el-col>
      <el-col :span="1.5">
        生成文章字数
        <el-input-number size="mini" v-model="txtlength"></el-input-number>
      </el-col>

      <el-col :span="1.5">
        算法模型
        <el-select
          v-model="useModel"
          placeholder="使用模型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.gpt_model"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-col>


    </el-row>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-tabs v-model="activeName" type="card" @tab-click="handTableClick">
        <el-tab-pane label="未洗稿" name="first"></el-tab-pane>
        <el-tab-pane label="已洗稿" name="second"></el-tab-pane>
        <el-tab-pane label="全部" name="all"></el-tab-pane>
      </el-tabs>




      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="来源" prop="sourceName">
        <el-select
          v-model="queryParams.sourceId"
          placeholder="选择来源名称"
          clearable
          style="width: 140px"
        >
          <el-option
            v-for="item in itemOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="类目" prop="className">
        <treeselect style="width: 140px" ref="optionClassRef"  @select="searchClassSelect" v-model="gform.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
      </el-form-item>




      <el-form-item label="发布时间" prop="createTime">

        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>




    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:spiderArticle:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['article:spiderArticle:edit']"-->
<!--        >导入</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="openImportTable">
          导入</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-opportunity"
          size="mini"
          @click="openGenTable">
          生成</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:spiderArticle:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:spiderArticle:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="startXigao"
          :disabled="multiple"
          :loading="piLiangxiGaoLoading"
        >批量洗稿</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-tooltip content="洗稿当前查询条件下所有文章" placement="top">
          <el-button
            type="primary"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="handleXigaoAll"
            :loading="allXiGaoLoading"
          >全部洗稿</el-button>
        </el-tooltip>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"

          @click="handleDeleteAll"
          v-hasPermi="['article:spiderArticle:remove']"
        >清空素材与生成内容</el-button>
      </el-col>

<!--      <el-col :span="1.5">-->
<!--      <template>-->
<!--        <el-alert-->
<!--          title="成功提示的文案"-->
<!--          type="success"-->
<!--          show-icon>-->
<!--        </el-alert>-->
<!--      </template>-->
<!--      </el-col>-->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spiderArticleList" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

<!--      <el-table-column label="文章标题" align="left" :show-overflow-tooltip="true" width="480">-->
<!--        <template slot-scope="scope">-->
<!--              <a :href="scope.row.spiderUrl" style=" color: #1890ff;" target="_blank"><span>{{ scope.row.title }}</span></a>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="文章标题" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <!--          <router-link :to="{name: 'article',params: {urlMd5: scope.row.urlMd5 }} " class="link-type">-->
          <router-link :to="'/article/viewArt/index/' + scope.row.urlMd5+'/spider'" class="link-type">
            <span>{{ scope.row.title }}</span>
          </router-link>
        </template>
      </el-table-column>




      <el-table-column label="来源名称" align="center" prop="sourceName" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.spider_articles_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="类目" align="center" prop="className" />
<!--      <el-table-column label="原文链接" align="center" :show-overflow-tooltip="true" prop="spiderUrl" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"

            :loading="scope.row.xiGaoLoading"
            icon="el-icon-refresh"
            @click="startXigao(scope.row)"
            v-hasPermi="['article:spiderArticle:edit']"
          >洗稿</el-button>
<!--          @click="startXigao(scope.row)"-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:spiderArticle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:spiderArticle:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采集文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="生成规则">
              <el-select v-model="form.spiderDiyId" ref="optionDiyRef"  placeholder="请选择生成/采集规则">
                <el-option
                  v-for="item in diyOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="生成模型">
              <el-select v-model="form.promptsId" ref="optionPromtsRef"  placeholder="请选择模型">
                <el-option
                  v-for="item in promptsOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="数据来源" prop="sourceId">
              <el-select v-model="form.sourceId" ref="optionItemRef"  placeholder="请选择来源">
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="文章分类" prop="classId">
              <treeselect style="width: 240px" ref="optionClassRef"  @select="addSelect" v-model="form.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="原文链接" prop="spiderUrl">
              <el-input v-model="form.spiderUrl" placeholder="请输入抓取的链接" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.spider_articles_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.artContent" :min-height="192"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入数据包 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".zip"
        :headers="upload.headers"
        :action="upload.url+ '?classId=' + form.classId +'&className='+form.className +'&promptsId='+form.promptsId +'&promptsName='+form.promptsName +'&sourceId='+form.sourceId +'&sourceName='+form.sourceName "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
<!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="文章分类" prop="classId">
                    <treeselect style="width: 240px" ref="optionClassRef"  @select="addSelect"  v-model="form.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
                  </el-form-item>
                </el-col>

            <el-col :span="12">
              <el-form-item label="生成模型">
                <el-select v-model="form.promptsId" @change="promptsChange($event)"  ref="optionPromtsRef"  placeholder="请选择模型">
                  <el-option
                    v-for="item in promptsOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="数据来源" prop="sourceId">
                <el-select v-model="form.sourceId" @change="sourceChange($event)"  ref="optionItemRef"  placeholder="请选择来源">
                  <el-option
                    v-for="item in itemOptions"
                    :key="item.id"
                    :label="item.name"

                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>


              </el-row>
            </el-form>

          </div>
          <span>仅允许导入zip格式文件,压缩包内支持解析txt、doc、docx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载包模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--文章生成-->

    <el-dialog :title="genform.title" :visible.sync="genform.open" width="600px" append-to-body>
      <el-form ref="gform" :model="gform" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="关键词" prop="remark">
              <el-input v-model="gform.genStyle" type="textarea" placeholder="请输入关键词用、隔开" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属分类" prop="classId">
              <treeselect style="width: 240px" ref="optionClassRef"  @select="gaddSelect" v-model="gform.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submotGenForn" :loading="genBtnLoading">确 定</el-button>
        <el-button @click="genform.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>


<script>
  import websocket from '@/utils/websocket'
import { listSpiderArticle, getSpiderArticle, delSpiderArticle, addSpiderArticle, updateSpiderArticle,spiderDiySelect,PromptsSelect,spiderItemSelect,toStartXigao,startXigaoAll,spiderClassSelect,genArticleByGpt,checkConnet,removeAll } from "@/api/article/spiderArticle";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

const baseURL = process.env.VUE_APP_BASE_API;
export default {
  name: "SpiderArticle",
  dicts: ['spider_articles_status','gpt_model'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      tuswitch:false,
      xituSwitch:false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedGptSpiderArticleContent: [],
      // 非单个禁用
      single: true,
      // 生成模型选项
      promptsOptions:[],
//分类选项
      spiderClassOptions:[],
      useModel:'gpt-3.5-turbo-16k',
      // 来源选项
      itemOptions: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 自定义规则
      diyOptions:[],
      piLiangxiGaoLoading:false,
      allXiGaoLoading:false,
      genBtnLoading:false,
      oneToNum:1,
      txtlength:1000,
      // 总条数
      total: 0,
      // 采集文章表格数据
      spiderArticleList: [],
      // 采集文章内容表格数据
      gptSpiderArticleContentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传用户时间范围
      daterangeCreateTime: [],
      //tab选项
      activeName: 'first',
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "上传数据包",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        classId: null,
        className:null,
        promptsId:null,
        promptsName:null,
        sourceId:null,
        sourceName: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/article/file/importData"
      },
      // 导入参数
      genform: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "生成文章",

        classId: null,
        className:null,

        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/article/file/genData"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promptsId:null,
        sourceId:null,
        sourceName:null,
        spiderDiyId:null,
        spiderDiyName:null,
        title: null,
        contentId: null,
        urlMd5: null,

        status: '0',
        spiderUrl: null,
        classId:null,
        className:null,
        createTime: null,
      },
      // 表单参数
      form: {},
      gform:{},

      // 表单校验
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        promptsId: [
          { required: true, message: "生成模型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        classId: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],

      }
    };
  },
  created() {
    this.getList();
    spiderItemSelect().then(response => {
      this.itemOptions = response.data;
    });
    spiderClassSelect().then(response => {
      this.spiderClassOptions = response.data;
    });
    console.log(baseURL);
    websocket.Init();
    this.getWebSocket();
  },
  methods: {


// websocket 接受消息
    getWebSocket() {
      let self = this;
      // websocket.getWebSocket()这个是websocket里面方法返回ws对象（websocket.js）
      try {
        let ws = websocket.getwebsocket();
        ws.onmessage = function(e){
          console.log('msg:' + e.data);
          let msg = e.data;
          if(typeof msg == 'string'){
            let obj = JSON.parse(msg);
            if(typeof obj == 'object' && obj){
              console.log("json",obj);
              let type = obj.type;
              if(type=='source'){
                self.setBtnLoading(msg)
              }
            }else{
              console.log("非json")
            }
          }else{
            console.log(msg)
          }


        }
      } catch (e) {
        console.log(e)
      }

    },
    setBtnLoading(msg){
      let obj = JSON.parse(msg);
      let type = obj.type;
      let id = obj.id;
      let percentage = obj.percentage;
      let status = obj.status;
      let datelists = this.spiderArticleList;
      let row = null;
      // this.spiderArticleList.forEach((item) => {
      //   console.log(item)
      // })
      for(var i in datelists){
        let rowli = datelists[i];
        if(id==rowli.id){
          row = rowli;
          break;
        }
      }
      if(status==2){
        console.log(row.id+"加载中.................."+id)
        this.$set(row, 'xiGaoLoading', true);
      }else if(status!=2){
        console.log("加载结束..................")
        this.$set(row, 'xiGaoLoading', false);
      }
      this.getList();
    },

    tableRowClassName({row, rowIndex}) {
      let beginDate = new Date(row.updateTime);
      let endDate = new Date();
      let minutes =(endDate - beginDate) / (1000 * 60);
      if(minutes<5){
        return 'success-row';
      }
      //
      // if (rowIndex === 1) {
      //   return 'warning-row';
      // } else if (rowIndex === 3) {
      //   return 'success-row';
      // }
      return '';
    },
    switchXituChange(value){
      console.log(value)
      if(value){
        checkConnet().then(response => {
          if(!response){
            this.xituSwitch=false;
            this.$modal.msgError("洗图服务暂不可用请查看参数配置！");
          }
        });
      }
    },
    /**洗稿按钮操作**/
    startXigao(row){
      const ids = row.id || this.ids;
      console.log(row);
      this.$set(row, 'xiGaoLoading', true);
      this.piLiangxiGaoLoading = true;
      this.allXiGaoLoading = true;

      let genPs = {
        oneToNum:this.oneToNum,
        txtlength:this.txtlength,
        tuswitch:this.tuswitch,
        xituSwitch:this.xituSwitch,
        useModel:this.useModel
      };
      // this.activeName= 'all';
      // this.queryParams.status = null;
      // this.getList();

      this.$modal.confirm('确定开始洗稿编号为"' + ids + '"的文章').then(function() {
        return toStartXigao(ids,genPs);
      }).then(() => {
        // this.messagetext = "test";
        // this.joinSocket();
        // this.sendMsg();
        // this.$set(row, 'xiGaoLoading', false);
        // this.piLiangxiGaoLoading = false;
        // this.allXiGaoLoading = false;
        this.$modal.msgSuccess("洗稿任务提交成功");
        this.activeName= 'all';
        this.queryParams.status = null;
        this.getList();
        this.close();
        // this.getList();


        // setTimeout("window.location.reload()", 1500 );

      }).catch(() => {
        console.log("end。。。")
        this.$set(row, 'xiGaoLoading', false);
        this.piLiangxiGaoLoading = false;
        this.allXiGaoLoading = false;

      });
    },
    handleXigaoAll(){
      console.log(typeof this.queryParams);
      /** 执行全量洗稿 */
      let genPs = {
        oneToNum:this.oneToNum,
        txtlength:this.txtlength,
        tuswitch:this.tuswitch,
        xituSwitch:this.xituSwitch,
        useModel:this.useModel
      };
      let sps = this.queryParams;
      console.log(sps)
      // this.$set(row, 'xiGaoLoading', true)
      this.piLiangxiGaoLoading = true;
      this.allXiGaoLoading = true;
      this.$modal.confirm('确定开始洗稿当前查询条件下所有文章？').then(function() {
        return startXigaoAll(sps,genPs);
      }).then(() => {
        this.$modal.msgSuccess("洗稿任务提交成功");
        this.activeName= 'all';
        this.queryParams.status = null;
        this.getList();
        // setTimeout("window.location.reload()", 1500 )
      }).catch(() => {
        // this.$set(row, 'xiGaoLoading', false);
        this.piLiangxiGaoLoading = false;
        this.allXiGaoLoading = false;
      });
    },


    handTableClick(tab, event) {

      switch (tab.name) {
        case "first":
          this.queryParams.status = '0';
          break;
        case "second":
            this.queryParams.status = '1';
            break;
        case "all":
              this.queryParams.status = null;
              break;
      }
      this.getList();
    },
    /**生成弹窗**/
    openGenTable(){
      // genform
      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
      this.greset();
      this.genform.title = "GPT模型比较器";
      this.genform.open = true;
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      // this.$refs.import.show();
      // alert();
      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
      /** 查询来源下拉框列表 */
      spiderItemSelect().then(response => {
        this.itemOptions = response.data;
      });
      /** 查询生成模型下拉框列表 */
      PromptsSelect().then(response => {
        this.promptsOptions = response.data;
      });
      this.reset();
      this.upload.title = "文章数据包上传";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
      this.$download.zip("/common/download?fileName=template.zip&delete=false" , "数据模板.zip");

    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询采集文章列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listSpiderArticle(this.queryParams).then(response => {
        this.spiderArticleList = response.rows;
        this.total = response.total;
        this.loading = false;

        this.$nextTick(() => {

          //处理按钮状态
          let datelists = this.spiderArticleList;
          let isallspider = false;
          for(var i in datelists){
            let row = datelists[i];
            if(row.status=="2"){
              this.$set(row, 'xiGaoLoading', true);
              this.piLiangxiGaoLoading = true;
              this.allXiGaoLoading = true;
              isallspider = true;
            }else{
              this.$set(row, 'xiGaoLoading', false);
            }
          }
          if(!isallspider){
            this.piLiangxiGaoLoading = false;
            this.allXiGaoLoading = false;
          }else{
            this.piLiangxiGaoLoading = true;
            this.allXiGaoLoading = true;
        }
        })


      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    greset(){
      this.gform = {
        genStyle:null,
        classId: null,
        className:null,
        oneToNum:1,
        txtlength:1000,
        useModel:'gpt-3.5-turbo-16k'
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        sourceId:null,
        sourceName: null,
        spiderDiyId:null,
        spiderDiyName:null,
        promptsId:null,
        contentId: null,
        urlMd5: null,

        status: "0",
        spiderUrl: null,
        classId: null,
        className:null,
        createTime: null,
        updateTime: null,
        artContent:null,
        remark: null
      };
      this.gptSpiderArticleContentList = [];
      this.resetForm("form");

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.daterangeCreateTime = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //分类选择框
    addSelect(value){
      this.form.className = value.label;
      console.log(this.className)
    },
    gaddSelect(value){
      this.gform.className = value.label;
    },
    searchClassSelect(value){
      this.queryParams.className = value.label;
      this.queryParams.classId = value.id;
    },
    sourceChange(value){
      var obj = {};
      //使用find()方法在下拉数据中根据value绑定的数据查找对象。
      obj = this.itemOptions.find(function(item){
        console.log(item)
        return item.id === value;
      });
      this.form.sourceName = obj.name;
    },
    promptsChange(value){
      var obj = {};
      //使用find()方法在下拉数据中根据value绑定的数据查找对象。
      obj = this.promptsOptions.find(function(item){
        console.log(item)
        return item.id === value;
      });
      this.form.promptsName = obj.name;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采集文章";

      /** 查询自定义采集下拉框列表 */
      spiderDiySelect().then(response => {
        this.diyOptions = response.data;
      });
      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
      /** 查询来源下拉框列表 */
      spiderItemSelect().then(response => {
        this.itemOptions = response.data;
      });
      /** 查询生成模型下拉框列表 */
      PromptsSelect().then(response => {
        this.promptsOptions = response.data;
      });

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      /** 查询自定义采集下拉框列表 */
      spiderDiySelect().then(response => {
        this.diyOptions = response.data;
      });
      /** 查询来源下拉框列表 */
      spiderItemSelect().then(response => {
        this.itemOptions = response.data;
      });
      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
      /** 查询生成模型下拉框列表 */
      PromptsSelect().then(response => {
        this.promptsOptions = response.data;
      });


      getSpiderArticle(id).then(response => {
        this.form = response.data;
        this.gptSpiderArticleContentList = response.data.gptSpiderArticleContentList;
        this.open = true;
        this.title = "修改采集文章";
      });
    },



    tests(){
      console.log("test")
    },
    //socket
    // joinSocket() {
    //   console.log("2222");
    //   // const wsuri = this.url;
    //   const wsuri = "ws://"+(window.location.origin.replace("http://",""))+":8080/websocket/message";
    //   console.log(wsuri);
    //   this.ws = new WebSocket(wsuri);
    //   console.log("连接中..");
    //   const self = this;
    //   this.ws.onopen = function (event) {
    //
    //     self.text_content = self.text_content + "已经打开连接!" + "\n";
    //   };
    //   this.ws.onmessage = function (event) {
    //     console.log(event.data)
    //     self.text_content = event.data + "\n";
    //
    //   };
    //
    //   this.ws.onclose = function (event) {
    //     self.text_content = self.text_content + "已经关闭连接!" + "\n";
    //   };
    // },
    // exit() {
    //   if (this.ws) {
    //     this.ws.close();
    //     this.ws = null;
    //   }
    // },
    // sendMsg() {
    //   if (this.ws) {
    //     this.ws.sendMsg(this.messagetext);
    //   } else {
    //     console.log("未连接到服务器");
    //   }
    // },
    // getMsg(){
    //
    // },

    submotGenForn(){
      // gform
      // let genPs = {
      //   oneToNum:this.oneToNum,
      //   txtlength:this.txtlength
      // };
      this.gform.oneToNum = this.oneToNum;
      this.gform.txtlength = this.txtlength;
      this.gform.useModel = this.useModel;
      this.genBtnLoading = true;
      this.$refs["gform"].validate(valid => {
        if (valid) {
          genArticleByGpt(this.gform).then(response => {
            this.$modal.msgSuccess("生成任务提交成功");
            this.genform.open = false;
            this.activeName= 'second';
            this.queryParams.status = '1';
            this.genBtnLoading = false;
            this.getList();
          });
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      var spiderDiyId =  this.$refs.optionDiyRef.selected.value;
      var promptsId =  this.$refs.optionPromtsRef.selected.value;
      var spiderDiyName =  this.$refs.optionDiyRef.selected.label;
      var promptsName =  this.$refs.optionPromtsRef.selected.label;
      var sourceName =  this.$refs.optionItemRef.selected.label;
      var sourceId =  this.$refs.optionItemRef.selected.value;

      this.form.spiderDiyId = spiderDiyId;
      this.form.promptsId = promptsId;
      this.form.spiderDiyName = spiderDiyName;
      this.form.promptsName = promptsName;

      this.form.sourceId = sourceId;
      this.form.sourceName = sourceName;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.gptSpiderArticleContentList = this.gptSpiderArticleContentList;
          if (this.form.id != null) {
            updateSpiderArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpiderArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采集文章编号为"' + ids + '"的数据项？').then(function() {
        return delSpiderArticle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDeleteAll(){
      this.$modal.confirm('确认清空所有素材以及生成内容，清空后将无法恢复？').then(function() {
        return removeAll();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("清空成功！");
      }).catch(() => {});
    },
	/** 采集文章内容序号 */
    rowGptSpiderArticleContentIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采集文章内容添加按钮操作 */
    handleAddGptSpiderArticleContent() {
      let obj = {};
      this.gptSpiderArticleContentList.push(obj);
    },
    /** 采集文章内容删除按钮操作 */
    handleDeleteGptSpiderArticleContent() {
      if (this.checkedGptSpiderArticleContent.length == 0) {
        this.$modal.msgError("请先选择要删除的采集文章内容数据");
      } else {
        const gptSpiderArticleContentList = this.gptSpiderArticleContentList;
        const checkedGptSpiderArticleContent = this.checkedGptSpiderArticleContent;
        this.gptSpiderArticleContentList = gptSpiderArticleContentList.filter(function(item) {
          return checkedGptSpiderArticleContent.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleGptSpiderArticleContentSelectionChange(selection) {
      this.checkedGptSpiderArticleContent = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/spiderArticle/export', {
        ...this.queryParams
      }, `spiderArticle_${new Date().getTime()}.xlsx`)
    },




  },



};
</script>
<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
